package com.aiyige.page.home;


import android.app.Activity;
import android.graphics.Rect;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.constraint.ConstraintLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.aiyige.R;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.BaseFragment;
import com.aiyige.base.api.ApiManager;
import com.aiyige.base.api.ResponseCode;
import com.aiyige.base.eventbus.EventLogin;
import com.aiyige.base.eventbus.EventLogout;
import com.aiyige.base.eventbus.EventRefreshHomePageBanner;
import com.aiyige.base.eventbus.EventSelectInterest;
import com.aiyige.base.eventbus.EventSelectRegion;
import com.aiyige.base.eventbus.EventTapBottomItemRefresh;
import com.aiyige.model.Page;
import com.aiyige.model.moment.entity.Moment;
import com.aiyige.model.sns.Follow;
import com.aiyige.page.home.adapter.HomeAdapter;
import com.aiyige.page.home.adapter.RecommendFollowAdapter;
import com.aiyige.page.home.adapter.RecommendFollowAdapterForGrid;
import com.aiyige.page.home.exception.NoContentException;
import com.aiyige.page.home.exception.NoMoreContentException;
import com.aiyige.page.home.model.FollowItem;
import com.aiyige.page.home.model.RecommendFollowResponse;
import com.aiyige.page.interest.model.Interest;
import com.aiyige.utils.AccountUtil;
import com.aiyige.utils.ErrorUtil;
import com.aiyige.utils.ListUtil;
import com.aiyige.utils.RetrofitUtil;
import com.aiyige.utils.SafeAsyncTask;
import com.aiyige.utils.StringUtils;
import com.aiyige.utils.ToastX;
import com.aiyige.utils.UIHelper;
import com.aiyige.utils.dialog.LoadingDialog;
import com.aiyige.utils.widget.CommonDataView;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.android.exoplayer2.C;
import com.netease.nim.uikit.common.util.string.StringUtil;

import net.cachapa.expandablelayout.ExpandableLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Response;

public class HomeFollowPage extends BaseFragment implements CommonDataView.RetrofitStub, HomeDataPageInterface {
    public static final int FROM_HAVE_FOLLOW_CONTENT = 1;
    public static final int FROM_NO_FOLLOW_CONTENT = 2;

    @BindView(R.id.loginLayout)
    ConstraintLayout loginLayout;
    @BindView(R.id.noFollowContentRv)
    RecyclerView noFollowContentRv;
    @BindView(R.id.noFollowContentSwipeRefreshLayout)
    SwipeRefreshLayout noFollowContentSwipeRefreshLayout;
    @BindView(R.id.noFollowContentLayout)
    FrameLayout noFollowContentLayout;
    @BindView(R.id.haveFollowContentCdv)
    CommonDataView haveFollowContentCdv;
    @BindView(R.id.haveFollowContentLayout)
    FrameLayout haveFollowContentLayout;
    @BindView(R.id.errorIv)
    ImageView errorIv;
    @BindView(R.id.errorTv)
    TextView errorTv;
    @BindView(R.id.loginBtn)
    TextView loginBtn;

    @BindView(R.id.errorLayout)
    View errorLayout;
    @BindView(R.id.loadingLayout)
    View loadingLayout;

    private Interest interest;
    private int sortWeight;
    private int position;
    Unbinder unbinder;
    HomeAdapter homeAdapter;
    Handler mainHandler;
    boolean haveFollow = false;
    boolean haveFollowPublish = false;
    long recommendFollowPageNum = 0;
    RecommendFollowAdapterForGrid recommendFollowAdapterForGrid;
    RecommendFollowAdapter recommendFollowAdapter;
    ExpandableLayout recommendFollowEmptyLayout;
    View refreshLayoutForGrid;
    View refreshLayout;
    View refreshBtnForGrid;
    View refreshBtn;
    RecyclerView haveFollowContentRecommendFollowRv;
    View haveFollowContentRecommndFollowLayout;

    public HomeFollowPage() {

    }

    public void initHeader() {
        recommendFollowAdapterForGrid.addHeaderView(LayoutInflater.from(getContext()).inflate(R.layout.home_follow_page_header_safe_line, (ViewGroup) noFollowContentRv.getParent(), false));
        recommendFollowEmptyLayout = (ExpandableLayout) LayoutInflater.from(getContext()).inflate(R.layout.recommend_follow_empty_layout, (ViewGroup) noFollowContentRv.getParent(), false);
        recommendFollowAdapterForGrid.addHeaderView(recommendFollowEmptyLayout);
        refreshLayoutForGrid = LayoutInflater.from(getContext()).inflate(R.layout.recommend_follow_refresh_layout, (ViewGroup) noFollowContentRv.getParent(), false);
        recommendFollowAdapterForGrid.addHeaderView(refreshLayoutForGrid);
        refreshBtnForGrid = refreshLayoutForGrid.findViewById(R.id.refreshBtn);
        refreshBtnForGrid.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new ChangeFollowForNoFollowContentTask(getActivity()).execute();
            }
        });

        homeAdapter.addHeaderView(LayoutInflater.from(getContext()).inflate(R.layout.home_follow_page_header_safe_line, (ViewGroup) haveFollowContentCdv.getRecyclerView().getParent(), false));
        refreshLayout = LayoutInflater.from(getContext()).inflate(R.layout.recommend_follow_refresh_layout, (ViewGroup) haveFollowContentCdv.getRecyclerView().getParent(), false);
        homeAdapter.addHeaderView(refreshLayout);
        refreshBtn = refreshLayout.findViewById(R.id.refreshBtn);
        refreshBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new ChangeFollowForHaveFollowContentTask(getActivity()).execute();
            }
        });

        haveFollowContentRecommndFollowLayout = LayoutInflater.from(getContext()).inflate(R.layout.have_follow_content_recommend_follow_layout, (ViewGroup) haveFollowContentCdv.getRecyclerView().getParent(), false);
        homeAdapter.addHeaderView(haveFollowContentRecommndFollowLayout);
        haveFollowContentRecommendFollowRv = haveFollowContentRecommndFollowLayout.findViewById(R.id.haveFollowContentRecommendFollowRv);
        recommendFollowAdapter = new RecommendFollowAdapter();
        haveFollowContentRecommendFollowRv.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                if (parent.getChildAdapterPosition(view) == 0) {
                    outRect.set(UIHelper.dip2px(10), 0, 0, 0);
                    return;
                } else if (parent.getChildAdapterPosition(view) == parent.getAdapter().getItemCount() - 1) {
                    outRect.set(0, 0, UIHelper.dip2px(10), 0);
                } else {
                    outRect.set(0, 0, 0, 0);
                }
            }
        });
        haveFollowContentRecommendFollowRv.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false));
        recommendFollowAdapter.bindToRecyclerView(haveFollowContentRecommendFollowRv);
        recommendFollowAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                FollowItem followItem = recommendFollowAdapter.getItem(position);
                if (!followItem.isFollowed()) {
                    new AddFollowTask(getActivity(), FROM_HAVE_FOLLOW_CONTENT, position).execute();
                } else {
                    new DeleteFollowTask(getActivity(), FROM_HAVE_FOLLOW_CONTENT, position).execute();
                }
            }
        });
        recommendFollowAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                FollowItem followItem = recommendFollowAdapter.getItem(position);
                ARouter.getInstance()
                        .build(ARouterConfig.UserPage)
                        .withString("userId", followItem.getId())
                        .navigation();
            }
        });
    }

    @Override
    public int getPosition() {
        return position;
    }

    @Override
    public void setPosition(int position) {
        this.position = position;
    }

    @Override
    public Interest getInterest() {
        return interest;
    }

    @Override
    public int getSortWeight() {
        return sortWeight;
    }

    @Override
    public void setSortWeight(int sortWeight) {
        this.sortWeight = sortWeight;
    }

    @Override
    public void setInterest(Interest interest) {
        this.interest = interest;
    }

    @Override
    public String getPageTitle() {
        return StringUtils.getString(R.string.follow);
    }

    public static HomeFollowPage newInstance(Interest interest, int sortWeight, int position) {
        HomeFollowPage fragment = new HomeFollowPage();
        fragment.setAutoRegisterEventBus(true);
        fragment.setInterest(interest);
        fragment.setSortWeight(sortWeight);
        fragment.setPosition(position);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.page_home_follow, container, false);
        unbinder = ButterKnife.bind(this, view);
        recommendFollowAdapterForGrid = new RecommendFollowAdapterForGrid();
        noFollowContentRv.setLayoutManager(new GridLayoutManager(container.getContext(), 3));
        recommendFollowAdapterForGrid.bindToRecyclerView(noFollowContentRv);
        recommendFollowAdapterForGrid.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                FollowItem followItem = recommendFollowAdapterForGrid.getItem(position);
                if (!followItem.isFollowed()) {
                    new AddFollowTask(getActivity(), FROM_NO_FOLLOW_CONTENT, position).execute();
                } else {
                    new DeleteFollowTask(getActivity(), FROM_NO_FOLLOW_CONTENT, position).execute();
                }
            }
        });
        recommendFollowAdapterForGrid.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                FollowItem followItem = recommendFollowAdapterForGrid.getItem(position);
                ARouter.getInstance()
                        .build(ARouterConfig.UserPage)
                        .withString("userId", followItem.getId())
                        .navigation();
            }
        });


        homeAdapter = new HomeAdapter();
        mainHandler = new Handler(Looper.getMainLooper());
        haveFollowContentCdv.config(homeAdapter, this);
        haveFollowContentCdv.setActionCallback(new CommonDataView.UserActionCallback() {
            @Override
            public void onUserRefresh() {
                recheckFollowContent();
            }

            @Override
            public void onUserLoadMore() {

            }
        });
        loginLayout.setVisibility(AccountUtil.isLogin() ? View.INVISIBLE : View.VISIBLE);
        try {
            if (!EventBus.getDefault().isRegistered(this)) {
                EventBus.getDefault().register(this);
            }
        } catch (Exception e) {

        }
        noFollowContentSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                recheckFollowContent();
            }
        });
        initHeader();
        return view;
    }


    public void showLoadingLayout() {
        loadingLayout.setVisibility(View.VISIBLE);
        errorLayout.setVisibility(View.INVISIBLE);
    }

    public void showErrorLayout() {
        loadingLayout.setVisibility(View.INVISIBLE);
        errorLayout.setVisibility(View.VISIBLE);
    }

    public void hideCoverLayout() {
        loadingLayout.setVisibility(View.INVISIBLE);
        errorLayout.setVisibility(View.INVISIBLE);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    protected void initData() {
        if (!AccountUtil.isLogin()) {
            loginLayout.setVisibility(View.VISIBLE);
        } else {
            loginLayout.setVisibility(View.INVISIBLE);
            checkFollowContent();
        }
    }

    public void recheckFollowContent() {
        recommendFollowPageNum = 0;
        if (AccountUtil.isLogin()) {
            new CheckFollowContentTask(getActivity(), false, true).execute();
        }
    }

    public void checkFollowContent() {
        recommendFollowPageNum = 0;
        new CheckFollowContentTask(getActivity(), true, false).execute();
    }

    public class CheckFollowContentTask extends SafeAsyncTask<Object, Object, Object> {
        boolean showLoading = false;
        boolean recheck = false;

        public CheckFollowContentTask(Activity activity, boolean showLoading, boolean recheck) {
            super(activity);
            this.showLoading = showLoading;
            this.recheck = recheck;
            if (showLoading) {
                showLoadingLayout();
            }
        }

        @Override
        public void safeOnPostExecute(Object o) {
            noFollowContentSwipeRefreshLayout.setRefreshing(false);
            if (o instanceof Exception) {
                EventBus.getDefault().post(EventTapBottomItemRefresh.newBuilder()
                        .itemType(EventTapBottomItemRefresh.ITEM_TYPE_HOME)
                        .actionType(EventTapBottomItemRefresh.ACTION_TYPE_REFRESH_FAILED)
                        .build());
                ToastX.show((Exception) o);
                if (showLoading) {
                    showErrorLayout();
                }
            } else {
                EventBus.getDefault().post(EventTapBottomItemRefresh.newBuilder()
                        .itemType(EventTapBottomItemRefresh.ITEM_TYPE_HOME)
                        .actionType(EventTapBottomItemRefresh.ACTION_TYPE_REFRESH_SUCCEED)
                        .build());
                if (showLoading) {
                    hideCoverLayout();
                }
                if (haveFollow && haveFollowPublish) {
                    haveFollowContentLayout.setVisibility(View.VISIBLE);
                    noFollowContentLayout.setVisibility(View.INVISIBLE);
                    if (!recheck || homeAdapter.getData().isEmpty()) {
                        haveFollowContentCdv.doRefreshRequest();
                    }
                    recommendFollowForHaveFollowContentLayout(showLoading);
                } else {
                    haveFollowContentLayout.setVisibility(View.INVISIBLE);
                    noFollowContentLayout.setVisibility(View.VISIBLE);
                    if (haveFollow) {
                        recommendFollowEmptyLayout.collapse(false);
                    } else {
                        recommendFollowEmptyLayout.expand(false);
                    }
                    recommendFollowForNoFollowContentLayout(showLoading);
                }
            }
        }


        @Override
        protected Object doInBackground(Object... objects) {
            try {
                {
                    Response<ResponseBody> response = ApiManager.getService().getFollowList(AccountUtil.getCurrentUser().getId(), 1, 0).execute();
                    if (response.code() != ResponseCode.OK) {
                        throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                    }
                    String json = RetrofitUtil.getResponseBodyAsString(response);
                    Page page = JSON.parseObject(json, Page.class);
                    List<Follow> tempFollowList = JSON.parseArray(page.getContent(), Follow.class);
                    haveFollow = !ListUtil.isEmpty(tempFollowList);
                }
                {
                    Response<ResponseBody> response = ApiManager.getService().recommendMommentList(Moment.MOMENT_LIST_TYPE_ATTENTION, 0, 1).execute();
                    if (response.code() != ResponseCode.OK) {
                        throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                    }
                    String json = RetrofitUtil.getResponseBodyAsString(response);
                    Page page = JSON.parseObject(json, Page.class);
                    List<Moment> momentList = JSON.parseArray(page.getContent(), Moment.class);
                    haveFollowPublish = !ListUtil.isEmpty(momentList);
                }
                return null;
            } catch (Exception e) {
                return e;
            }
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(EventLogin event) {
        if (AccountUtil.isLogin()) {
            loginLayout.setVisibility(View.INVISIBLE);
            checkFollowContent();
        } else {
            loginLayout.setVisibility(View.VISIBLE);
            homeAdapter.setNewData(new LinkedList<Moment>());
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(EventLogout event) {
        loginLayout.setVisibility(View.VISIBLE);
        homeAdapter.setNewData(new LinkedList<Moment>());
    }

    @Override
    protected void onVisible() {
        if (!isFirstLoad()) {
            recheckFollowContent();
        }
        super.onVisible();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (!isFirstLoad() && isFragmentVisible() && AccountUtil.isLogin()) {
            recheckFollowContent();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventSelectRegion(EventSelectRegion event) {
       // haveFollowContentCdv.doRefreshRequest();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(EventTapBottomItemRefresh event) {
        if (isFragmentVisible()
                && event.getItemType() == EventTapBottomItemRefresh.ITEM_TYPE_HOME
                && event.getActionType() == EventTapBottomItemRefresh.ACTION_TYPE_START_REFRESH
                && event.getInterest().equals(interest)) {
            mainHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (AccountUtil.isLogin()) {
                        recheckFollowContent();
                    } else {
                        EventBus.getDefault().post(EventTapBottomItemRefresh.newBuilder()
                                .itemType(EventTapBottomItemRefresh.ITEM_TYPE_HOME)
                                .actionType(EventTapBottomItemRefresh.ACTION_TYPE_REFRESH_SUCCEED)
                                .build());
                    }
                }
            }, 1000);
        }


    }

    public void recommendFollowForNoFollowContentLayout(boolean showLoading) {
        new RecommendFollowForNoFollowContentTask(getActivity(), showLoading).execute();
    }

    public void recommendFollowForHaveFollowContentLayout(boolean showLoading) {
        new RecommendFollowForHaveFollowContentTask(getActivity(), showLoading).execute();
    }


    public class RecommendFollowForNoFollowContentTask extends SafeAsyncTask<Object, Object, Object> {
        List<FollowItem> followItemList = new LinkedList<>();
        boolean showLoading;

        public RecommendFollowForNoFollowContentTask(Activity activity, boolean showLoading) {
            super(activity);
            this.showLoading = showLoading;
            if (showLoading) {
                showLoadingLayout();
            }
        }

        @Override
        public void safeOnPostExecute(Object o) {
            if (o instanceof NoMoreContentException) {
                if (showLoading) {
                    hideCoverLayout();
                }
            } else if (o instanceof Exception) {
                ToastX.show((Exception) o);
                if (showLoading) {
                    showErrorLayout();
                }
            } else {
                if (showLoading) {
                    hideCoverLayout();
                }
                recommendFollowAdapterForGrid.setNewData(followItemList);
            }
        }

        @Override
        protected Object doInBackground(Object... objects) {
            try {
                Response<ResponseBody> response = ApiManager.getService().recommendFollow(recommendFollowPageNum++, 12).execute();
                if (response.code() != ResponseCode.OK) {
                    throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                }
                String json = RetrofitUtil.getResponseBodyAsString(response);
                Page page = JSON.parseObject(json, Page.class);
                if (page.getTotalPages() <= recommendFollowPageNum) {
                    recommendFollowPageNum = 0;
                }
                List<RecommendFollowResponse> recommendFollowResponseList = JSON.parseArray(page.getContent(), RecommendFollowResponse.class);
                if (ListUtil.isEmpty(recommendFollowResponseList)) {
                    recommendFollowPageNum = 0;
                    throw new NoMoreContentException(StringUtils.getString(R.string.no_more_content));
                }
                for (RecommendFollowResponse recommendFollowResponse : recommendFollowResponseList) {
                    followItemList.add(FollowItem.newBuilder()
                            .id(recommendFollowResponse.getId())
                            .name(recommendFollowResponse.getAccount())
                            .avatar(recommendFollowResponse.getAvatar())
                            .followed(false)
                            .build());
                }
                return null;
            } catch (Exception e) {
                return e;
            }
        }
    }

    public class ChangeFollowForNoFollowContentTask extends SafeAsyncTask<Object, Object, Object> {
        List<FollowItem> followItemList = new LinkedList<>();

        public ChangeFollowForNoFollowContentTask(Activity activity) {
            super(activity, R.string.loading);
        }

        @Override
        public void safeOnPostExecute(Object o) {
            if (o instanceof NoMoreContentException) {

            } else if (o instanceof Exception) {
                ToastX.show((Exception) o);
            } else {
                recommendFollowAdapterForGrid.setNewData(followItemList);
            }
        }

        @Override
        protected Object doInBackground(Object... objects) {
            try {
                Response<ResponseBody> response = ApiManager.getService().recommendFollow(recommendFollowPageNum++, 12).execute();
                if (response.code() != ResponseCode.OK) {
                    throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                }
                String json = RetrofitUtil.getResponseBodyAsString(response);
                Page page = JSON.parseObject(json, Page.class);
                if (page.getTotalPages() <= recommendFollowPageNum) {
                    recommendFollowPageNum = 0;
                }
                List<RecommendFollowResponse> recommendFollowResponseList = JSON.parseArray(page.getContent(), RecommendFollowResponse.class);
                if (ListUtil.isEmpty(recommendFollowResponseList)) {
                    recommendFollowPageNum = 0;
                    throw new NoMoreContentException(StringUtils.getString(R.string.no_more_content));
                }
                for (RecommendFollowResponse recommendFollowResponse : recommendFollowResponseList) {
                    followItemList.add(FollowItem.newBuilder()
                            .id(recommendFollowResponse.getId())
                            .name(recommendFollowResponse.getAccount())
                            .avatar(recommendFollowResponse.getAvatar())
                            .followed(false)
                            .build());
                }
                return null;
            } catch (Exception e) {
                return e;
            }
        }
    }


    public class RecommendFollowForHaveFollowContentTask extends SafeAsyncTask<Object, Object, Object> {
        List<FollowItem> followItemList = new LinkedList<>();
        boolean showLoading;

        public RecommendFollowForHaveFollowContentTask(Activity activity, boolean showLoading) {
            super(activity);
            this.showLoading = showLoading;
            if (showLoading) {
                showLoadingLayout();
            }
        }

        @Override
        public void safeOnPostExecute(Object o) {
            if (showLoading) {
                hideCoverLayout();
            }
            if (o instanceof NoMoreContentException) {
                //ToastX.show((Exception) o);
            } else if (o instanceof NoContentException) {
                refreshLayout.setVisibility(View.GONE);
                haveFollowContentRecommndFollowLayout.setVisibility(View.GONE);
            } else if (o instanceof Exception) {
                refreshLayout.setVisibility(View.GONE);
                haveFollowContentRecommndFollowLayout.setVisibility(View.GONE);
                ToastX.show((Exception) o);
            } else {
                refreshLayout.setVisibility(View.VISIBLE);
                haveFollowContentRecommndFollowLayout.setVisibility(View.VISIBLE);
                recommendFollowAdapter.setNewData(followItemList);
            }
        }

        @Override
        protected Object doInBackground(Object... objects) {
            try {
                boolean firstPage = recommendFollowPageNum == 0;
                Response<ResponseBody> response = ApiManager.getService().recommendFollow(recommendFollowPageNum++, 12).execute();
                if (response.code() != ResponseCode.OK) {
                    throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                }
                String json = RetrofitUtil.getResponseBodyAsString(response);
                Page page = JSON.parseObject(json, Page.class);
                if (page.getTotalPages() <= recommendFollowPageNum) {
                    recommendFollowPageNum = 0;
                }
                List<RecommendFollowResponse> recommendFollowResponseList = JSON.parseArray(page.getContent(), RecommendFollowResponse.class);
                if (ListUtil.isEmpty(recommendFollowResponseList)) {
                    recommendFollowPageNum = 0;
                    if (firstPage) {
                        throw new NoContentException(StringUtils.getString(R.string.no_result));
                    } else {
                        throw new NoMoreContentException(StringUtils.getString(R.string.no_more_content));
                    }
                }
                for (RecommendFollowResponse recommendFollowResponse : recommendFollowResponseList) {
                    followItemList.add(FollowItem.newBuilder()
                            .id(recommendFollowResponse.getId())
                            .name(recommendFollowResponse.getAccount())
                            .avatar(recommendFollowResponse.getAvatar())
                            .followed(false)
                            .build());
                }
                return null;
            } catch (Exception e) {
                return e;
            }
        }
    }

    public class ChangeFollowForHaveFollowContentTask extends SafeAsyncTask<Object, Object, Object> {
        List<FollowItem> followItemList = new LinkedList<>();

        public ChangeFollowForHaveFollowContentTask(Activity activity) {
            super(activity);
        }

        @Override
        public void safeOnPostExecute(Object o) {
            if (o instanceof NoMoreContentException) {

            } else if (o instanceof NoContentException) {
                refreshLayout.setVisibility(View.GONE);
                haveFollowContentRecommndFollowLayout.setVisibility(View.GONE);
            } else if (o instanceof Exception) {
                ToastX.show((Exception) o);
            } else {
                recommendFollowAdapter.setNewData(followItemList);
                haveFollowContentRecommendFollowRv.scrollToPosition(0);
            }
        }

        @Override
        protected Object doInBackground(Object... objects) {
            try {
                boolean firstPage = recommendFollowPageNum == 0;
                Response<ResponseBody> response = ApiManager.getService().recommendFollow(recommendFollowPageNum++, 12).execute();
                if (response.code() != ResponseCode.OK) {
                    throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                }
                String json = RetrofitUtil.getResponseBodyAsString(response);
                Page page = JSON.parseObject(json, Page.class);
                if (page.getTotalPages() <= recommendFollowPageNum) {
                    recommendFollowPageNum = 0;
                }
                List<RecommendFollowResponse> recommendFollowResponseList = JSON.parseArray(page.getContent(), RecommendFollowResponse.class);
                if (ListUtil.isEmpty(recommendFollowResponseList)) {
                    recommendFollowPageNum = 0;
                    if (firstPage) {
                        throw new NoContentException("");
                    } else {
                        throw new NoMoreContentException(StringUtils.getString(R.string.no_more_content));
                    }
                }
                for (RecommendFollowResponse recommendFollowResponse : recommendFollowResponseList) {
                    followItemList.add(FollowItem.newBuilder()
                            .id(recommendFollowResponse.getId())
                            .name(recommendFollowResponse.getAccount())
                            .avatar(recommendFollowResponse.getAvatar())
                            .followed(false)
                            .build());
                }
                return null;
            } catch (Exception e) {
                return e;
            }
        }
    }


    @Override
    public Call<ResponseBody> call(long currentPage) {
        return ApiManager.getService().recommendMommentList(Moment.MOMENT_LIST_TYPE_ATTENTION, currentPage, 15);
    }

    @Override
    public CommonDataView.HandleResult handleResponse(String respJson, List resultList) {
        try {
            Page page = JSON.parseObject(respJson, Page.class);
            List<Moment> momentList = new LinkedList<>();
            if (!TextUtils.isEmpty(page.getContent())) {
                momentList.addAll(JSON.parseArray(page.getContent(), Moment.class));
            }
            for (Moment moment : momentList) {
                resultList.add(new Moment(moment));
            }
            return new CommonDataView.HandleResult(page.isLast());
        } catch (Exception e) {
            return new CommonDataView.HandleResult(e.getMessage());
        }

    }

    @OnClick({R.id.loginBtn, R.id.errorLayout})
    public void onViewClicked(View v) {
        switch (v.getId()) {
            case R.id.loginBtn:
                ARouter.getInstance().build(ARouterConfig.LoginPage).navigation();
                break;
            case R.id.errorLayout:
                if (haveFollow && haveFollowPublish) {
                    recommendFollowForHaveFollowContentLayout(true);
                } else {
                    recommendFollowForNoFollowContentLayout(true);
                }
                break;
        }
    }


    public class AddFollowTask extends SafeAsyncTask<Object, Object, Object> {
        String targetId;
        int from;
        int position;
        String followId;

        public AddFollowTask(Activity activity, int from, int position) {
            super(activity, R.string.loading);
            this.from = from;
            switch (from) {
                case FROM_HAVE_FOLLOW_CONTENT:
                    targetId = recommendFollowAdapter.getItem(position).getId();
                    break;
                case FROM_NO_FOLLOW_CONTENT:
                    targetId = recommendFollowAdapterForGrid.getItem(position).getId();
                    break;
                default:
                    targetId = "";
                    break;
            }

            this.position = position;
            followId = "";
        }

        @Override
        public void safeOnPostExecute(Object o) {
            if (o instanceof Exception) {
                ToastX.show(((Exception) o).getMessage());
            } else {
                switch (from) {
                    case FROM_HAVE_FOLLOW_CONTENT:
                        try {
                            FollowItem followItem = recommendFollowAdapter.getItem(position);
                            followItem.setFollowId(followId);
                            followItem.setFollowed(true);
                            recommendFollowAdapter.setData(position, followItem);
                        } catch (Exception e) {
                        }
                        break;
                    case FROM_NO_FOLLOW_CONTENT:
                        try {
                            FollowItem followItem = recommendFollowAdapterForGrid.getItem(position);
                            followItem.setFollowId(followId);
                            followItem.setFollowed(true);
                            recommendFollowAdapterForGrid.setData(position, followItem);
                            recommendFollowEmptyLayout.collapse();
                        } catch (Exception e) {
                        }
                        break;
                }
            }
        }

        @Override
        protected Object doInBackground(Object... objects) {
            try {
                Response<ResponseBody> response = ApiManager.getService().addFollow(Follow.newBuilder()
                        .beFollowedId(targetId)
                        .followerId(AccountUtil.getCurrentUser().getId())
                        .build())
                        .execute();
                if (response.code() != ResponseCode.CREATED) {
                    throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                }
                String json = RetrofitUtil.getResponseBodyAsString(response);
                Follow follow = JSON.parseObject(json, Follow.class);
                if (follow == null) {
                    throw new Exception("添加关注失败");
                }
                followId = follow.getId();
                return null;
            } catch (Exception e) {
                return e;
            }
        }
    }

    public class DeleteFollowTask extends SafeAsyncTask<Object, Object, Object> {
        int from;
        String followId;
        int position;

        public DeleteFollowTask(Activity activity, int from, int position) {
            super(activity, R.string.loading);
            this.from = from;
            this.position = position;
            switch (from) {
                case FROM_HAVE_FOLLOW_CONTENT:
                    this.followId = recommendFollowAdapter.getItem(position).getFollowId();
                    break;
                case FROM_NO_FOLLOW_CONTENT:
                    this.followId = recommendFollowAdapterForGrid.getItem(position).getFollowId();
                    break;
                default:
                    this.followId = "";
                    break;
            }

        }

        @Override
        protected Object doInBackground(Object... objects) {
            try {
                Response<ResponseBody> response = ApiManager.getService()
                        .deleteFollow(followId)
                        .execute();
                if (response.code() != ResponseCode.NO_CONTENT) {
                    throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                }
                return null;
            } catch (Exception e) {
                return e;
            }
        }


        @Override
        public void safeOnPostExecute(Object o) {
            if (o instanceof Exception) {
                ToastX.show(((Exception) o).getMessage());
            } else {
                switch (from) {
                    case FROM_HAVE_FOLLOW_CONTENT: {
                        FollowItem followItem = recommendFollowAdapter.getItem(position);
                        followItem.setFollowed(false);
                        followItem.setFollowId("");
                        recommendFollowAdapter.setData(position, followItem);
                        break;
                    }
                    case FROM_NO_FOLLOW_CONTENT: {
                        FollowItem followItem = recommendFollowAdapterForGrid.getItem(position);
                        followItem.setFollowed(false);
                        followItem.setFollowId("");
                        recommendFollowAdapterForGrid.setData(position, followItem);
                        break;
                    }
                }
            }
        }
    }


}
